package com.example.demo.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashExample {
	public static String compute(byte[] data, String algorithm) {
		try {
			// 创建一个MessageDigest实例用于SHA-256
			MessageDigest digest = MessageDigest.getInstance(algorithm);

			// 使用数据更新摘要
			digest.update(data);

			// 完成哈希计算
			byte[] hash = digest.digest();

			// 将哈希值转换为十六进制字符串
			StringBuilder hexString = new StringBuilder();
			for (byte b : hash) {
				String hex = Integer.toHexString(0xff & b);
				if (hex.length() == 1)
					hexString.append('0');
				hexString.append(hex);
			}

			// 输出哈希值
			return hexString.toString();
		} catch (NoSuchAlgorithmException e) {
			return "";
		}
	}
}
